import 'dart:async';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_response_bean.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_view_model.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_model_page.dart';
import 'package:e_reception_flutter/ui/ai_poster/change_to_diy_page_event.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_page.dart';
import 'package:e_reception_flutter/ui/common/bean/diy_center_info_response_bean.dart';
import 'package:e_reception_flutter/ui/common/common_view_model.dart';
import 'package:e_reception_flutter/ui/common/update_diy_center_info_event.dart';
import 'package:e_reception_flutter/ui/course_intro/course_intro_index_page.dart';
import 'package:e_reception_flutter/ui/product_show/product_show_index_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_list_page.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import '../business_application_info_page.dart';
import 'ai_poster_diy_page.dart';
import 'ai_poster_diy_view_model.dart';
import 'diy_poster_count_event.dart';

/// ai海报首页
class AiPosterIndexPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "AiPosterIndexPage";

  @override
  AiPosterIndexPageState createState() => AiPosterIndexPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult(
      context,
      AiPosterIndexPage(),
      routeName: AiPosterIndexPage.ROUTER,
    );
  }
}

class AiPosterIndexPageState
    extends BasePagerState<AiPosterIndexListItemBean, AiPosterIndexPage>
    with
        AutomaticKeepAliveClientMixin,
        VgPlaceHolderStatusMixin,
        NavigatorPageMixin {

  AiPosterIndexViewModel viewModel;
  AiPosterDiyViewModel diyViewModel;
  StreamSubscription _aiPosterStreamSubscription;
  StreamSubscription _diyPosterStreamSubscription;
  StreamSubscription _changePageStreamSubscription;
  StreamSubscription _updateDiyCenterInfoStreamSubscription;
  PageController _pageController;
  ValueNotifier<int> _pageValueNotifier;
  int _diyCount = 0;

  CommonViewModel _commonViewModel;
  DiyCenterInfoData _diyCenterInfoData;
  ComIndustryApplicationBean _businessApplicationData;

  ///获取state
  static AiPosterIndexPageState of(BuildContext context) {
    final AiPosterIndexPageState result =
    context.findAncestorStateOfType<AiPosterIndexPageState>();
    return result;
  }


  @override
  void initState() {
    super.initState();
    viewModel = AiPosterIndexViewModel(this);
    diyViewModel = AiPosterDiyViewModel(this);
    _commonViewModel = CommonViewModel(this);
    _commonViewModel.getBusinessApplicationInfo();
    diyViewModel.refresh();
    _pageValueNotifier = ValueNotifier(0);
    _pageController = PageController(keepPage: true, initialPage: 0);
    _pageController?.addListener(_setCurrentPage);
    viewModel?.refresh();
    _aiPosterStreamSubscription =
        VgEventBus.global.on<MonitoringAiPosterIndexClass>()?.listen((event) {
          viewModel?.refresh();
          diyViewModel?.refresh();
          _commonViewModel.getBusinessApplicationInfo();
        });

    _diyPosterStreamSubscription =
        VgEventBus.global.on<DiyPosterCount>()?.listen((event) {
          setState(() {
            _diyCount = event?.count??0;
          });
        });
    _changePageStreamSubscription =
        VgEventBus.global.on<ChangeToDiyPageEvent>()?.listen((event) {
          _animToPage(1);
        });
    _updateDiyCenterInfoStreamSubscription =
        VgEventBus.global.on<UpdateDiyCenterInfoEvent>()?.listen((event) {
          _commonViewModel.getBusinessApplicationInfo();
        });
    _commonViewModel.diyCenterInfoValueNotifier.addListener(() {
      _businessApplicationData = _commonViewModel?.diyCenterInfoValueNotifier?.value?.comIndustryApplication;
      setState(() { });
    });
  }

  @override
  void dispose() {
    _aiPosterStreamSubscription?.cancel();
    _diyPosterStreamSubscription?.cancel();
    _changePageStreamSubscription?.cancel();
    _updateDiyCenterInfoStreamSubscription?.cancel();
    _pageController?.removeListener(_setCurrentPage);
    _pageController?.dispose();
    _pageValueNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: Column(
        children: [
          SizedBox(height: ScreenUtils.getStatusBarH(context),),
          _toTitleWidget(),
          _toTopBarWidget(),
          _toPosterModuleIndexWidget(),
          Expanded(child: _toPageWidget()),
          // Expanded(child: _toMainColumnWidget()),
        ],
      ),
    );
  }

  Widget _toTitleWidget(){
    return Container(
      margin: EdgeInsets.only(left: 15,),
      alignment: Alignment.centerLeft,
      height: 44,
      child: Row(
        children: [
          Text(
            "行业应用",
            style: TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.w600,
                color: ThemeRepository.getInstance().getTextColor_D0E0F7()
            ),
          ),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              BusinessApplicationInfoPage.navigatorPush(context, _businessApplicationData);
            },
            child: Row(
              children: [
                Text(
                (_businessApplicationData == null)?"使用中·0":_businessApplicationData?.getUseInfo(),
                  style: TextStyle(
                      fontSize: 14,
                      color: ThemeRepository.getInstance().getTextColor_D0E0F7()
                  ),
                ),
                SizedBox(width: 9,),
                Image.asset(
                  "images/icon_arrow_right_grey.png",
                  width: 6,
                ),
                SizedBox(width: 15,),
              ],
            ),
          )
        ],
      ),

    );
  }

  Widget _toTopBarWidget(){
    return ValueListenableBuilder(
      valueListenable: _commonViewModel.diyCenterInfoValueNotifier,
      builder: (BuildContext context, DiyCenterInfoData data, Widget child){
        if(data != null){
          _diyCenterInfoData = data;
          _businessApplicationData = data?.comIndustryApplication;
        }
        return  Container(
            alignment: Alignment.center,
            height: 90,
            decoration: BoxDecoration(
              color: Color(0xFFE7F3FF),
              borderRadius: BorderRadius.circular(8),
              // border: Border.all(
              //     color: Color(0xFF404664),
              //     width: 0.5),
            ),
            margin: EdgeInsets.only(left: 15, right: 15, top: 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _toMenuItemWidget("楼层指示牌", "images/lczsp.png", _businessApplicationData?.isOpenBuildingIndex()??false, _onClickLCZSP),
                _toMenuItemWidget("智能家居", "images/znjj.png", _businessApplicationData?.isOpenSmartHome()??false, _onClickZNJJ),
                _toMenuItemWidget("商品展示", "images/spzs.png", _businessApplicationData?.isOpenGoodsShow()??false, _onClickSPZS),
                _toMenuItemWidget("课程介绍", "images/kcjs.png", _businessApplicationData?.isOpenCourseIntro()??false, _onClickKCJS),
              ],
            ));
      },
    );

  }

  Widget _toMenuItemWidget(String title, String resource, bool isOpen, VoidCallback onClick){
    return GestureDetector(
      onTap: (){
        onClick.call();
      },
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(width: 9,),
                  Image.asset(
                    resource,
                    width: 44,
                    height: 44,
                  ),
                  Container(width: 9,)
                ],
              ),
              SizedBox(height: 3,),
              Text(
                title,
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance().getCardBgColor_21263C()
                ),
              ),
            ],
          ),
          Visibility(
              visible: isOpen,
              child: _usingWidget()
          ),
        ],
      ),
    );
  }

  ///使用中布局
  Widget _usingWidget(){
    return Positioned(
      top: 13,
      right: 0,
      child: Container(
        height: 14,
        width: 34,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Color(0xFF00C6C4),
          borderRadius: BorderRadius.circular(7),
          border: Border.all(
              color: Colors.white,
              width: 1),
        ),
        child: Text(
          "使用中",
          style: TextStyle(
              fontSize: 9,
              color: Colors.white,
              height: 1.2
          ),
        ),
      ),
    );
  }

  ///点击楼层指示牌
  void _onClickLCZSP(){
    BuildingIndexPage.navigatorPush(context, _diyCenterInfoData?.comWBrandCnt);
  }

  ///点击智能家居
  void _onClickZNJJ(){
    SmartHomeStoreListPage.navigatorPush(context);
  }

  ///点击商品展示
  void _onClickSPZS(){
    ProductShowIndexPage.navigatorPush(context);
  }

  ///点击课程介绍
  void _onClickKCJS(){
    CourseIntroIndexPage.navigatorPush(context);
  }


  Widget _toPosterModuleIndexWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          alignment: Alignment.centerLeft,
          height: 54,
          padding: EdgeInsets.only(left: 15),
          child: Text(
            "海报制作模板",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                fontSize: 17,
                height: 1.1,
                fontWeight: FontWeight.w600),
          ),
        ),
        Spacer(),
        Visibility(
            visible: _diyCount>0,
            child: _toChangeWidget()
        ),
        SizedBox(width: 15,)
      ],
    );
  }

  ///切换
  Widget _toChangeWidget(){
    return ValueListenableBuilder(
        valueListenable: _pageValueNotifier,
        builder: (BuildContext context, int page, Widget child){
          return Container(
            width: 129,
            height: 24,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              border: Border.all(
                  color: ThemeRepository.getInstance()
                      .getPrimaryColor_1890FF(),
                  width: 0.5),
              color: Colors.transparent,
            ),
            child: Row(
              children: [
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: (){
                    _animToPage(0);
                  },
                  child: Container(
                    width: 64,
                    height: 24,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      border: Border.all(
                          width: 0.5,
                          color: (page == 0)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                          Colors.transparent
                      ),
                      color: (page == 0)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                      Colors.transparent,
                      borderRadius: (page == 0)?BorderRadius.circular(4):BorderRadius.circular(0),
                    ),
                    child: Text(
                      "全部",
                      style: TextStyle(
                        color: (page == 0)?Colors.white:ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                        fontSize: 12,
                      ),
                    ),
                  ),
                ),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: (){
                    _animToPage(1);
                  },
                  child: Container(
                    width: 64,
                    height: 24,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      border: Border.all(
                          width: 0.5,
                          color: (page == 1)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                          Colors.transparent
                      ),
                      color: (page == 1)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                      Colors.transparent,
                      borderRadius: (page == 1)?BorderRadius.circular(4):BorderRadius.circular(0),
                    ),
                    child: Text(
                      ((_diyCount??0)>99)?"已制作99":"已制作${_diyCount??0}",
                      style: TextStyle(
                        color: (page == 1)?Colors.white:ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                        fontSize: 12,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          );
        }
    );


  }

  void _animToPage(int page){
    if(page != 1 && page != 0){
      return;
    }
    _pageController?.animateToPage(page, duration: DEFAULT_ANIM_DURATION, curve: Curves.linear);
  }

  void _setCurrentPage(){
    if(_diyCount < 1){
      return;
    }
    if(_pageController.page >= 0.51){
      _pageValueNotifier.value = 1;
    }else if(_pageController.page <=0.49){
      _pageValueNotifier.value = 0;
    }
    // _pageValueNotifier.value = widget?.pageController?.page?.floor();
  }

  Widget _toPageWidget(){
    if(_diyCount>0){
      return PageView(
        controller: _pageController,
        physics: ClampingScrollPhysics(),
        children: <Widget>[
          AiPosterModelPage(),
          AiPosterDiyPage(),
        ],
      );
    }else{
      return AiPosterModelPage();
    }

  }

  Widget _toMainColumnWidget() {
    return  MixinPlaceHolderStatusWidget(
        emptyOnClick: () => viewModel?.refresh(),
        errorOnClick: () => viewModel.refresh(),
        // child: child,
        child: VgPullRefreshWidget.bind(
            state: this, viewModel: viewModel, child: _toGridPage())
    );
  }


  Widget _toGridPage(){
    return GridView.builder(
      padding: EdgeInsets.only(
          left: 15,
          right: 15,
          top: 3,
          bottom: getNavHeightDistance(context)
      ),
      itemCount: data?.length ?? 0,
      physics: BouncingScrollPhysics(),
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 5,
        crossAxisSpacing: 5,
        childAspectRatio: 1 / 1.73,
      ),
      itemBuilder: (BuildContext context, int index) {
        return _toGridItemWidget(context,data?.elementAt(index));
      },
    );
  }


  Widget _toGridItemWidget(BuildContext context, AiPosterIndexListItemBean itemBean) {
    return ClickBackgroundWidget(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        // AiPosterDetailPage.navigatorPush(context, itemBean);
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: AspectRatio(
          aspectRatio: 1,
          child: Container(
            color: Colors.black,
            child: Stack(
              alignment: Alignment.center,
              children: <Widget>[
                VgCacheNetWorkImage(itemBean?.getPicUrl() ?? "",imageQualityType: ImageQualityType.middleDown,),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
